#include "audio/data/OggFile.h"

#define STB_VORBIS_HEADER_ONLY
#include "stb_vorbis.c"

using namespace Audio::Core;

OggFile::OggFile(const std::string &path)
    : m_Path(path)
{
    Init();
};

bool OggFile::Init()
{
    int error;

    vorbis = stb_vorbis_open_filename(m_Path.c_str(), &error, NULL);
    if (!vorbis)
    {
        ztclog::warn("Failed to open OGG file '%s', error code: %d\n", m_Path.c_str(), error);
        return false;
    }

    stb_vorbis_info info = stb_vorbis_get_info(vorbis);
    ztclog::warn("Channels: %d, Sample Rate: %d\n", info.channels, info.sample_rate);

    // 读取整个音频数据
    int total_samples = stb_vorbis_stream_length_in_samples(vorbis);
    pcm = (float *)malloc(total_samples * info.channels * sizeof(float));
    if (!pcm)
    {
        ztclog::warn("Failed to allocate memory for PCM data\n");
        stb_vorbis_close(vorbis);
        return 1;
    }

    int samples_decoded = stb_vorbis_get_samples_float(vorbis, info.channels, &pcm, total_samples * info.channels);
    ztclog::warn("Decoded %d samples\n", samples_decoded);

    return true;
}
void OggFile::Free()
{
    free(pcm);
    stb_vorbis_close(vorbis);
}